﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.rtgs.stp_record_detail_i_repair" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RTGS.Library.Enum;
using RTGS.Library.DataAccess.Rtgs;
using RTGS.Library.Entities.Rtgs;
using RTGS.Web.support;
using System.Configuration;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;
namespace RTGS.Web.ajaxhandler.rtgs
{
    public class stp_record_detail_i_repair : BaseHandler
    {
        private stpRecordDetailIRepo stpRecordDal = new stpRecordDetailIRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("getmemberbycode"):
                    context.Response.Write(GetMemberByCode(context));
                    break;
                case ("getaccountmemberbycode"):
                    context.Response.Write(GetAccountMemberByCode(context));
                    break;
                case ("getnamememberbycode"):
                    context.Response.Write(GetNameMemberByCode(context));
                    break;
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                case ("repair"):
                    context.Response.Write(Repair(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler


        private string Update(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            stpRecordDetailI obj = new stpRecordDetailI();

            ////GROUP TRN
            //if(context.Request.Params["trn"]!=null)
            //    obj.recordDetailItrTrn = context.Request.Params["trn"];
            //if (context.Request.Params["relatedTrn"] != null)
            //    obj.recordDetailItrRelatedtrn = context.Request.Params["relatedTrn"];

            //////GROUP AMOUNT
            //if (context.Request.Params["amount"] != null && context.Request.Params["amount"] != "")
            //    obj.recordDetailItrAmount = Convert.ToDecimal(context.Request.Params["amount"]).ToString();
            //if (context.Request.Params["currency"] != null)
            //    obj.recordDetailIstCurrency = context.Request.Params["currency"];
            //if (context.Request.Params["bussinesDay"] != null)
            //{
            //    if (context.Request.Params["bussinesDay"].Contains("/"))
            //    {
            //        string[] splitTanggal = context.Request.Params["bussinesDay"].ToString().Trim().Split('/');

            //        obj.recordDetailItrValuedate = splitTanggal[2].ToString() + splitTanggal[1].ToString() + splitTanggal[0].ToString();
            //    }
            //    else
            //        obj.recordDetailItrValuedate = context.Request.Params["bussinesDay"];
                
            //}

            //////GROUP DEBIT PARTICIPANT
            //if (context.Request.Params["debitParticipant"] != null)
            //    obj.recordDetailIstFromaccountname = context.Request.Params["debitParticipant"];
            //if (context.Request.Params["accountDebitParticipant"] != null)
            //    obj.recordDetailIstFromaccountnumber = context.Request.Params["accountDebitParticipant"];
            //if (context.Request.Params["memberCodeDebit"] != null)
            //    obj.recordDetailItrFrommember = context.Request.Params["memberCodeDebit"];


            //////GROUP CREDIT PARTICIPANT
            //if (context.Request.Params["creditParticipant"] != null)
            //    obj.recordDetailIstToaccountname = context.Request.Params["creditParticipant"];
            //if (context.Request.Params["accountCreditParticipant"] != null)
            //    obj.recordDetailIstToaccountnumber= context.Request.Params["accountCreditParticipant"];
            //if (context.Request.Params["memberCodeCredit"] != null)
            //    obj.recordDetailItrTomember = context.Request.Params["memberCodeCredit"];

            //////GROUP DEBIT PARTICIPANTS CLIENT
            //if (context.Request.Params["debitParticipantsClient"] != null)
            //{
            //    if (context.Request.Params["debitParticipantsClient"].ToString().Trim().Length > 140)
            //        //obj.recordDetailOstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
            //        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
            //    else
            //        //obj.recordDetailOstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();
            //        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();
            //}

            //if (context.Request.Params["accountDebitParticipantsClient"] != null)
            //    obj.recordDetailIstOriginatingnumber = context.Request.Params["accountDebitParticipantsClient"];


            //////GROUP CREDIT PARTICIPANTS CLIENT
            //if (context.Request.Params["creditParticipantsClient"] != null)
            //{
            //    if (context.Request.Params["creditParticipantsClient"].ToString().Trim().Length > 140)
            //        obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString().Substring(0, 140);
            //    //obj.recordDetailOtrTomember = context.Request.Params["creditParticipantsClient"].ToString().Substring(0, 17);
            //    else
            //        obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString();
            //    //obj.recordDetailOtrTomember = context.Request.Params["creditParticipantsClient"].ToString();
            //}

            //if (context.Request.Params["accountParticipantsClient"] != null)
            //    obj.recordDetailIstUltimatebenefaccount = context.Request.Params["accountParticipantsClient"];




            //////GROUP DETAIL
            //if (context.Request.Params["remitanceInformation"] != null)
            //{
            //    if (context.Request.Params["remitanceInformation"].ToString().Trim().Length > 96)
            //        obj.recordDetailIstPaymentdetails = context.Request.Params["remitanceInformation"].ToString().Substring(0, 96);
            //    else
            //        obj.recordDetailIstPaymentdetails = context.Request.Params["remitanceInformation"].ToString();
            //}

            //if (context.Request.Params["detailOfCharges"] != null)
            //    obj.recordDetailItrRecordtype = context.Request.Params["detailOfCharges"];
            //if (context.Request.Params["transactionSubTypeCode"] != null)
            //    obj.recordDetailItrTransactioncode = context.Request.Params["transactionSubTypeCode"];

            //////GROUP PRIORITY
            ////if (context.Request.Params["priority"] != null)
            ////    obj.recordDetailOrecordPriority = context.Request.Params["priority"];

            //obj.recordDetailIrecordSwiftIdatetime = DateTime.Now;
            //obj.recordDetailIrecordtime = DateTime.Now;
            //obj.recordDetailIrecordIhBatchreference = string.Empty;
            //obj.recordDetailIcompletionstatus = string.Empty;



            //if (stpRecordDal.Update(obj))
            //{
            //    helper.Data = obj;
            //    helper.Message = "Data has been saved!";
            //    helper.IsSuccess = true;

            //    log = new sysTLog();
            //    log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR Success";
            //    log.logMessage = string.Empty;
            //}
            //else
            //{
            //    helper.IsSuccess = false;
            //    helper.Message = stpRecordDal.GetErrorMessage();

            //    log = new sysTLog();
            //    log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR  Error";
            //    log.logMessage = stpRecordDal.GetErrorMessage();


            //}

            //log.logSource = "stp_record_detail_i_repair.ashx";
            //log.createdBy = base.UserLoggedIn;
            //log.createdDate = DateTime.Now;
            //logDal.Save(log);


          

           
                obj.recordDetailIstStatus = "RP";
                obj.recordDetailItrRelatedtrn = context.Request.Params["Id"];
                obj.recordDetailIstPaymentdetails = context.Request.Params["sender"].ToString().Trim();
                if (context.Request.Params["reasoncode"].ToString() == "011")
                {
                    

                    if (context.Request.Params["creditParticipantsClient"].ToString().Trim().Length > 140)
                        obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString().Substring(0, 140);
                    else
                        obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString();

                    obj.recordDetailIstUltimatebenefaccount = context.Request.Params["accountParticipantsClient"];


                }

                if (context.Request.Params["reasoncode"].ToString() == "012")
                {

                    if (context.Request.Params["debitParticipantsClient"].ToString().Trim().Length > 140)
                        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
                    else
                        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();

                    obj.recordDetailIstOriginatingnumber = context.Request.Params["accountDebitParticipantsClient"];
                }

          



            if (stpRecordDal.UpdateIncomingRepair(obj, context.Request.Params["reasoncode"].ToString().Trim()))
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRecordDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR  Error";
                log.logMessage = string.Empty;

            }

            log.logSource = "spt_record_detail_i_repair.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);


            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        private string Repair(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            stpRecordDetailI obj = new stpRecordDetailI();

            obj.recordDetailIstStatus = "RT";
            obj.recordDetailItrRelatedtrn = context.Request.Params["Id"];
            if(context.Request.Params["sender"].ToString().Trim().Length>96)
                obj.recordDetailIstPaymentdetails = context.Request.Params["sender"].ToString().Trim().Substring(0,95);
            else
                obj.recordDetailIstPaymentdetails = context.Request.Params["sender"].ToString().Trim();
            
            if (context.Request.Params["reasoncode"].ToString() == "011")
            {


                if (context.Request.Params["creditParticipantsClient"].ToString().Trim().Length > 140)
                    obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString().Substring(0, 140);
                else
                    obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString();

                obj.recordDetailIstUltimatebenefaccount = context.Request.Params["accountParticipantsClient"];


            }

            if (context.Request.Params["reasoncode"].ToString() == "012")
            {

                if (context.Request.Params["debitParticipantsClient"].ToString().Trim().Length > 140)
                    obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
                else
                    obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();

                obj.recordDetailIstOriginatingnumber = context.Request.Params["accountDebitParticipantsClient"];
            }





            if (stpRecordDal.UpdateIncomingRepair(obj, context.Request.Params["reasoncode"].ToString().Trim()))
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRecordDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I_REPAIR  Error";
                log.logMessage = string.Empty;

            }

            log.logSource = "spt_record_detail_i_repair.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);


            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        private string GetData(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);
            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);
            string sidx = ((context.Request.QueryString["sidx"]) == null ? stpRecordDetailI.Fields.recordDetailItrRelatedtrn : context.Request.QueryString["sidx"].ToString());
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());
            string parameters = string.Empty;

            string valuedate = ((context.Request.Params["valuedate"]) == null ? string.Empty : context.Request.QueryString["valuedate"].ToString());
            string trn = ((context.Request.Params["trn"]) == null ? string.Empty : context.Request.QueryString["trn"].ToString());
            string batchref = ((context.Request.Params["batchref"]) == null ? string.Empty : context.Request.QueryString["batchref"].ToString());
            string status = ((context.Request.Params["status"]) == null ? string.Empty : context.Request.QueryString["status"].ToString());
            string refno = ((context.Request.Params["refno"]) == null ? string.Empty : context.Request.QueryString["refno"].ToString());
            string tomember = ((context.Request.Params["tomember"]) == null ? string.Empty : context.Request.QueryString["tomember"].ToString());


            parameters = !string.IsNullOrEmpty(valuedate) ?
            (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ITR_ValueDate LIKE '%" + valuedate + "%'" : " WHERE RECORD_DETAIL_ITR_ValueDate LIKE '%" + valuedate + "%'")
                      : parameters;

            parameters = !string.IsNullOrEmpty(trn) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ITR_TRN LIKE '%" + trn + "%'" : " WHERE RECORD_DETAIL_ITR_TRN LIKE '%" + trn + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(batchref) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_IRECORD_IH_BatchReference LIKE '%" + batchref + "%'" : " WHERE RECORD_DETAIL_IRECORD_IH_BatchReference LIKE '%" + batchref + "%'")
                                 : parameters;


            parameters = !string.IsNullOrEmpty(status) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_IST_Status LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_IST_Status LIKE '%" + status + "%'")
                                 : parameters;

            //parameters = !string.IsNullOrEmpty(refno) ?
            //       (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_RefNo LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_ORECORD_RefNo LIKE '%" + refno + "%'")
            //                     : parameters;

            parameters = !string.IsNullOrEmpty(tomember) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ITR_ToMember LIKE '%" + tomember + "%'" : " WHERE RECORD_DETAIL_ITR_ToMember LIKE '%" + tomember + "%'")
                                 : parameters;


            parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_IST_Status) = 'RF' " : " WHERE UPPER(RECORD_DETAIL_IST_Status) = 'RF'";

            int totalCount = Convert.ToInt32(stpRecordDal.SelectScalar(SQL.Function.Aggregate.Count, stpRecordDetailI.Fields.recordDetailItrRelatedtrn, parameters));
            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);
            List<stpRecordDetailI> pagedList = stpRecordDal.GetList(pageSize, page, sidx, sord, parameters);

            var query = from incoming in pagedList
                        //join product in productDTO on subproduct.productId equals product.id
                        select new
                        {
                            incoming.recordDetailItrRelatedtrn,
                            incoming.recordDetailItrValuedate,
                            incoming.recordDetailIstStatus,
                            incoming.recordDetailIstRsncde,
                            incoming.recordDetailItrTomember,
                            incoming.recordDetailItrTrn,
                            recordDetailItrAmount = incoming.recordDetailItrAmount == string.Empty ? string.Empty : Convert.ToDecimal(incoming.recordDetailItrAmount).ToString("#,###.00")


                        };

            if (!string.IsNullOrEmpty(stpRecordDal.GetErrorMessage()))
            {

                log = new sysTLog();
                log.logEvent = "GetData STP_RECORD_DETAIL_I_INCOMING Success";
                log.logMessage = string.Empty;

            }
            else
            {
                log = new sysTLog();
                log.logEvent = "View Data STP_RECORD_DETAIL_I_INCOMING  Error";
                log.logMessage = string.Empty;
            }

            log.logSource = "stp_record_detail_i_incoming.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = query,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        public string GetMemberByCode(HttpContext context)
        {
            base.ProcessRequest(context);

            RTGS.Library.Report.ReportSptDetailRecordO reportDal = new RTGS.Library.Report.ReportSptDetailRecordO(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

            string membercode = Convert.ToString(context.Request.Params["membercode"]);

            System.Data.DataTable dt = reportDal.GetMemberByMemberCode(membercode);
            //List<rExchangeRateDTO> list = mgr.GetListDTO();
            //var result = list.Where(x => x.exchangeRateTypeId == jeniskurs);

            string result = string.Empty;

            if (dt.Rows.Count > 0)
                result = dt.Rows[0]["memcde"].ToString().Trim();// +"=" + dt.Rows[0]["accnbr"].ToString().Trim();

            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }


        public string GetAccountMemberByCode(HttpContext context)
        {
            base.ProcessRequest(context);

            RTGS.Library.Report.ReportSptDetailRecordO reportDal = new RTGS.Library.Report.ReportSptDetailRecordO(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

            string membercode = Convert.ToString(context.Request.Params["membercode"]);

            System.Data.DataTable dt = reportDal.GetMemberByMemberCode(membercode);
            //List<rExchangeRateDTO> list = mgr.GetListDTO();
            //var result = list.Where(x => x.exchangeRateTypeId == jeniskurs);

            string result = string.Empty;

            if (dt.Rows.Count > 0)
                result = dt.Rows[0]["accnbr"].ToString().Trim();

            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }

        public string GetNameMemberByCode(HttpContext context)
        {
            base.ProcessRequest(context);

            RTGS.Library.Report.ReportSptDetailRecordO reportDal = new RTGS.Library.Report.ReportSptDetailRecordO(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

            string membercode = Convert.ToString(context.Request.Params["membercode"]);

            System.Data.DataTable dt = reportDal.GetMemberByMemberCode(membercode);

            string result = string.Empty;

            if (dt.Rows.Count > 0)
                result = dt.Rows[0]["memname"].ToString().Trim();

            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }


        #endregion


    }
}
